<script setup lang="tsx">
import { h, ref } from 'vue';
import { NButton, NTag } from 'naive-ui';
import { $t } from '@/locales';
import { fetchGetOAuth2TokenList } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useAuth } from '@/hooks/business/auth';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import OAuth2TokenSearch from './modules/token-search.vue';

const wrapperRef = ref<HTMLElement | null>(null);
const appStore = useAppStore();
const { hasAuth } = useAuth();

const { columns, data, loading, mobilePagination, getData, getDataByPage, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetOAuth2TokenList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    username: '',
    authorizationGrantType: '',
    clientId: ''
  },
  columns: () => [
    {
      key: 'clientId',
      title: $t('page.manage.oauth2.token.clientId'),
      align: 'center',
      width: 150,
      render: row => {
        return <NTag>{row.clientId}</NTag>;
      }
    },
    {
      key: 'accessToken',
      title: $t('page.manage.oauth2.token.accessToken'),
      align: 'center',
      width: 300,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'refreshToken',
      title: $t('page.manage.oauth2.token.refreshToken'),
      align: 'center',
      width: 300,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'username',
      title: $t('page.manage.oauth2.token.username'),
      align: 'center',
      width: 150
    },
    {
      key: 'authorizationGrantType',
      title: $t('page.manage.oauth2.token.authorizationGrantType'),
      align: 'center',
      width: 150,
      render: row => {
        if (row.authorizationGrantType === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_OAUTH2_GRANT_TYPE, row.authorizationGrantType);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'accessTokenIssuedAt',
      title: $t('page.manage.oauth2.token.accessTokenIssuedAt'),
      align: 'center',
      width: 220
    },
    {
      key: 'accessTokenExpiresAt',
      title: $t('page.manage.oauth2.token.accessTokenExpiresAt'),
      align: 'center',
      width: 220
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 100,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:oauth2-token:delete')}>
            <NButton type="primary" ghost size="small" onClick={() => handleForceLogout(row.id)}>
              {{
                default: () => $t('page.manage.oauth2.token.forcedRetreat'),
                icon: () => h(SvgIcon, { icon: 'vaadin:exit' })
              }}
            </NButton>
          </div>
        </div>
      )
    }
  ]
});

const { onDeleted } = useTableOperate(data, getData);

/** 强制退出操作 */
function handleForceLogout(id: number) {
  try {
    // 二次确认
    window.$dialog?.info({
      title: $t('page.manage.oauth2.token.forcedRetreat'),
      content: $t('page.manage.oauth2.token.forcedRetreatWhether'),
      positiveText: $t('common.confirm'),
      negativeText: $t('common.cancel'),
      onPositiveClick: () => {
        // 发起删除

        window.$message?.success($t('common.success'));
        // 刷新列表
        onDeleted(null);
      }
    });
  } catch {}
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <OAuth2TokenSearch
      v-if="hasAuth('system:oauth2-token:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard
      :title="$t('page.manage.oauth2.token.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <NDataTable
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="2088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>
  </div>
</template>
